<template>
  <div class="customer-confirm-contract-detail">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>合同详情</h2>
<!--        <button @click="goBack" class="btn btn-secondary">-->
<!--          <i class="fa fa-arrow-left mr-2"></i>返回列表-->
<!--        </button>-->
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载合同中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <div v-if="contract && !loading" class="card mt-4">
      <div class="card-body">
        <!-- 合同详情 - 上半部分 -->
        <h3 class="contract-name">{{ contract.name }}</h3>
        <div class="contract-info">
          <p><strong>合同ID:</strong> {{ contract.id }}</p>
          <p><strong>项目经理:</strong> {{ projectManagerName }}</p>
          <p><strong>状态:</strong> {{ formatStatus(contract.status) }}</p>
          <p><strong>创建时间:</strong> {{ formatDate(contract.createTime) }}</p>
          <p><strong>更新时间:</strong> {{ formatDate(contract.updateTime) }}</p>
        </div>

        <div class="clauses-section mt-4">
          <h4>条款列表</h4>
          <div v-if="clauses.length > 0" class="clauses-list">
            <ul class="list-group">
              <li
                  v-for="clause in clauses"
                  :key="clause.id"
                  class="list-group-item"
              >
                <p class="mb-1"><strong>内容:</strong> {{ clause.content }}</p>
              </li>
            </ul>
          </div>
          <div v-else class="empty-message text-center py-2">
            <i class="fa fa-info-circle text-muted mr-2"></i>暂无条款
          </div>
        </div>
      </div>
    </div>

    <!-- 确认合同区域 - 下半部分 -->
    <div class="confirm-area mt-4 card">
      <div class="card-body">
        <h4 class="mb-4">确认合同</h4>

        <div class="d-flex gap-3 mb-4">
          <button
              @click="downloadContractPdf"
              class="btn btn-info flex-grow"
              :disabled="loadingPdf"
          >
            <i class="fa fa-download mr-2"></i>下载合同PDF
          </button>
          <button
              @click="confirmContract"
              class="btn btn-success flex-grow"
              :disabled="loading || contract.status !== 'PENDING_CONFIRMATION'"
          >
            <i class="fa fa-check mr-2"></i>确认合同
          </button>
        </div>

        <div v-if="confirmSuccess" class="alert alert-success">
          <i class="fa fa-check-circle mr-2"></i>合同确认成功！
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'CustomerConfirmContractDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()

    const contractId = ref(route.params.contractId)
    const contract = ref(null)
    const clauses = ref([])
    const errorMessage = ref('')
    const loading = ref(true)
    const confirmSuccess = ref(false)
    const loadingPdf = ref(false)

    // 获取项目经理名称
    const projectManagerName = computed(() => {
      return contract.value?.projectManager?.name || '未指定'
    })

    // 状态映射
    const statusMap = {
      "PENDING_CONFIRMATION": "待确认",
      "CONFIRMED": "已确认",
      "DRAFT": "草稿",
      "PENDING_REVIEW": "待审核",
      "PENDING_FINANCE_AUDIT": "待财务审核",
      "REVIEW_FAILED": "审核失败",
      "COMPLETED": "已完成"
    }

    // 获取合同详情
    const fetchContractDetails = () => {
      loading.value = true
      errorMessage.value = ''

      if (!contractId.value) {
        errorMessage.value = '缺少合同ID参数'
        setTimeout(() => {
          router.push('/customer/confirm-contracts')
        }, 2000)
        loading.value = false
        return
      }

      axios.get(`/auth/contracts/${contractId.value}/customer-confirm`)
          .then(response => {
            contract.value = response.data
          })
          .catch((err) => {
            console.error('获取合同详情失败', err)
            errorMessage.value = '获取合同详情失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 获取条款
    const fetchClauses = () => {
      if (!contractId.value) {
        console.log('合同ID不存在，无法获取条款')
        return
      }

      axios.get(`/auth/clauses/contract/${contractId.value}`)
          .then(response => {
            clauses.value = response.data
          })
          .catch((err) => {
            console.error('获取合同条款失败', err)
            errorMessage.value = '获取合同条款失败，请重试'
          })
    }

    // 下载合同PDF
    const downloadContractPdf = () => {
      loadingPdf.value = true
      axios.get(`/auth/documents/contracts/${contractId.value}/pdf`, {
        responseType: 'blob'
      })
          .then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]))
            const link = document.createElement('a')
            link.href = url
            link.setAttribute('download', `${contract.value?.name}.pdf`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
          .catch(error => {
            console.error('下载PDF失败', error)
            errorMessage.value = '下载合同PDF失败，请重试'
          })
          .finally(() => {
            loadingPdf.value = false
          })
    }

    // 确认合同
    const confirmContract = () => {
      if (contract.value.status !== 'PENDING_CONFIRMATION') {
        errorMessage.value = '该合同当前状态无法确认'
        return
      }

      loading.value = true

      axios.put(`/auth/contracts/${contractId.value}/confirm`)
          .then(() => {
            confirmSuccess.value = true
            errorMessage.value = ''
          })
          .catch(error => {
            console.error('确认合同失败', error)
            errorMessage.value = error.response?.data?.message || '确认合同失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 返回列表
    const goBack = () => {
      router.push('/customer/confirm-contracts')
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    // 格式化状态
    const formatStatus = (statusCode) => {
      return statusMap[statusCode] || statusCode
    }

    onMounted(() => {
      fetchContractDetails()
      fetchClauses()
    })

    return {
      contractId,
      contract,
      clauses,
      errorMessage,
      loading,
      confirmSuccess,
      loadingPdf,
      projectManagerName,
      goBack,
      formatDate,
      formatStatus,
      downloadContractPdf,
      confirmContract
    }
  }
}
</script>

<style scoped>
/* 样式与之前的合同详情页面相似，可复用 */
.customer-confirm-contract-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  color: #721c24;
  background-color: #f8d7da;
  border-left: 4px solid #f5c6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.card {
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.card-body {
  padding: 20px;
}

.contract-name {
  margin-bottom: 20px;
  font-size: 1.5rem;
  color: #333;
}

.contract-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.contract-info p {
  margin: 5px 0;
  flex: 1 1 300px;
}

.clauses-section h4 {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
}

.clauses-list {
  margin-bottom: 0;
}

.empty-message {
  color: #6c757d;
  font-style: italic;
  padding: 10px 0;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-primary {
  background-color: #0d6efd;
  color: white;
  border: none;
}

.btn-primary:hover {
  background-color: #0b5ed7;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 123, 255, 0.2);
}

.btn-info {
  background-color: #17a2b8;
  color: white;
  border: none;
}

.btn-info:hover {
  background-color: #138496;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(23, 162, 184, 0.2);
}

.btn-success {
  background-color: #28a745;
  color: white;
  border: none;
}

.btn-success:hover {
  background-color: #218838;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(40, 167, 69, 0.2);
}

.confirm-area {
  margin-top: 30px;
}
</style>